#include "common_product_definition.h"
#include "base_log.h"
#include <iostream>

namespace El {
namespace Common {

// 辅助函数，去除字符串两端的双引号
std::string RemoveQuotes(const std::string& str) {
    if (str.length() >= 2 && str.front() == '"' && str.back() == '"') {
        return str.substr(1, str.length() - 2);
    }
    return str;
}

ProductDefinition &ProductDefinition::GetInstance()
{
    static ProductDefinition instance;
    return instance;
}

bool ProductDefinition::LoadFromFile(const std::string &yamlFile)
{
    try {
        Base::YamlParser parser;
        if (!parser.LoadFromFile(yamlFile)) {
            LOG_ERROR("Invalid product definition format in file: {}", yamlFile.c_str());
            return false;
        }
        config_ = parser.GetRoot();
        return true;
    } catch (const std::exception &e) {
        LOG_ERROR("YAML error while loading file {}: {}", yamlFile.c_str(), e.what());
        config_ = Base::YamlValue(std::map<std::string, Base::YamlValue>()); // 重置为空配置
        return false;
    }
}

bool ProductDefinition::GetValue(const std::string &key, std::string &value) const
{
    try {
        auto yamlValue = config_.Get(key);
        if (!yamlValue.IsString()) {
            return false;
        }
        value = RemoveQuotes(yamlValue.AsString());
        return true;
    } catch (const std::exception &) {
        return false;
    }
}

bool ProductDefinition::GetValue(const std::string &key, std::vector<std::string> &value) const
{
    try {
        auto yamlValue = config_.Get(key);
        if (!yamlValue.IsArray()) {
            LOG_ERROR("key is not array: {}", key.c_str());
            return false;
        }

        const auto &array = yamlValue.AsArray();
        value.clear();
        for (const auto &item : array) {
            if (item.IsString()) {
                value.push_back(RemoveQuotes(item.AsString()));
            }
        }
        return !value.empty();
    } catch (const std::exception &) {
        LOG_ERROR("key is not array: {}", key.c_str());
        return false;
    }
}

} // namespace Common
} // namespace El